﻿using HuaweiCloud.Dotnet.Samples.Common.Cache.Extension;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Dtos;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Entities;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Service;
using Microsoft.Extensions.Caching.Distributed;
using System.Collections;
using System.Collections.Generic;

namespace HuaweiCloud.Dotnet.Samples.ESports.Main.Manager
{
    public class RankManager : IRankManager
    {
        private readonly IUserService _userService;

        private readonly IDistributedCache _cache;
        private string _key = RedisConst.Rank;
        public RankManager(IUserService userService, IDistributedCache cache)
        {
            _userService = userService;
            _cache = cache;
        }
        public async Task<List<RankDto>> GetDailyRankAsync(CancellationToken token = default)
        {
            // 创建列表
            var res = new List<RankDto>();
            // 根据当天日期生成缓存的Key
            var key = $"{_key}-{DateTime.Today.ToString("yyyy-MM-dd")}";
            // 缓存获取排行榜
            var rank = await _cache.GetAsync<Rank>(key, token);
            if (rank != null && rank.Data != null)
            {
                // 通过用户id列表获取对应的用户信息列表
                var users = await _userService.GetUsersByIdsAsync(rank.Data.Keys.ToArray());
                var map = users?.Data;
                foreach(var k in rank.Data.Keys)
                    res.Add(new RankDto(map?[k], rank.Data[k]));
            }
            // 创建降序排序规则
            var comparer = Comparer<RankDto>.Create((x, y) => x.Count - y.Count);
            // 排序
            res.Sort(comparer);
            return res;
        }
    }
}
